# // ============================================================================
# // File: scripts/install.sh
# // ============================================================================
#!/bin/bash
set -e

echo "Installing Onyx Snapshotter..."

# Build binary
go build -o /usr/local/bin/onyx-snapshotter ./cmd/onyx-snapshotter

# Create directories
mkdir -p /etc/onyx
mkdir -p /var/lib/onyx
mkdir -p /run/onyx
mkdir -p /var/log

# Copy config
cp config/config.yaml /etc/onyx/

# Create systemd service
cat > /etc/systemd/system/onyx-snapshotter.service <<EOF
[Unit]
Description=Onyx Snapshotter for Containerd
After=containerd.service
Requires=containerd.service

[Service]
Type=simple
ExecStart=/usr/local/bin/onyx-snapshotter \\
  --config /etc/onyx/config.yaml \\
  --address /run/onyx/onyx.sock \\
  --log-level info
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd
systemctl daemon-reload

# Configure containerd to use onyx snapshotter
echo "Configuring containerd..."
# 删除已存在的 onyx 配置段（如果存在）
sed -i '/## onyx begin/,/## onyx end/d' /etc/containerd/config.toml

# 追加新的 onyx 插件配置
cat >> /etc/containerd/config.toml <<EOF

## onyx begin
[proxy_plugins]
  [proxy_plugins.onyx]
    type = "snapshot"
    address = "/run/onyx/onyx.sock"
## onyx end
EOF

echo "Installation complete!"
echo ""
echo "To start Onyx Snapshotter:"
echo "  sudo systemctl start onyx-snapshotter"
echo ""
echo "To use with containerd:"
echo "  sudo systemctl restart containerd"
echo "  ctr run --snapshotter=onyx docker.io/library/alpine:latest test-container"